<template>
  <div class="editor-upload-container">
    <el-button type="primary" size="small" @click="upload">上传图片</el-button>
    <el-dialog
      v-model="dialogVisible"
      custom-class="editor-upload-dialog"
      @closed="closeDialog"
    >
      <el-upload
        :multiple="true"
        :file-list="defaultList"
        :show-file-list="true"
        :headers="header"
        :action="uploadUrl"
        list-type="picture-card"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :before-upload="beforeUpload"
      >
        <el-button size="small" type="primary">Click upload</el-button>
      </el-upload>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
  import { ElMessage } from 'element-plus'
  import { ref, defineEmits, unref } from 'vue'
  import { useUpload, uploadNetTools } from '@/hooks/elementUI/useUpload.js'
  const defaultList = ref([])
  // 存放对象
  const listObj = ref({})
  const dialogVisible = ref(false)
  const emit = defineEmits(['uploadImages'])

  const upload = function () {
    dialogVisible.value = true
  }
  const closeDialog = function () {
    listObj.value = {}
    defaultList.value = []
  }

  const { checkAllSuccess, removeFile, uploadSuccess, uploadBefore } =
    useUpload(listObj)
  const { header, uploadUrl } = uploadNetTools()
  // 上传文件
  const handleSubmit = function (params) {
    const arr = Object.keys(listObj.value).map((v) => listObj.value[v])
    if (!checkAllSuccess()) {
      ElMessage.info({ message: '还有图片未上传完毕' })
      return
    }
    emit('uploadImages', arr)
    dialogVisible.value = false
  }
  const handleRemove = function (file) {
    removeFile(file)
  }

  const handleSuccess = function (response, file) {
    uploadSuccess(response, file)
  }
  const beforeUpload = function (file) {
    return uploadBefore(file)
  }
</script>
<style lang="scss">
  .editor-upload-container {
    position: absolute;
    right: 4px;
    top: 4px;
    z-index: 100;
    .editor-upload-dialog {
      margin-bottom: 20px;
      .el-upload--picture-card {
        width: 100%;
      }
    }
  }
</style>
